import { inject, type Ref, watch } from 'vue'
import { Config, useAccount, useAccountEffect, useDisconnect } from '@wagmi/vue'
import { DesktopModalConstant, MobileModalConstant } from '../constants/ModalContextConstant'
import { clearLatestWalletId } from '../wallets/latestWalletId'
import { isMobile } from '../utils/isMobile'

export function useConnectModal(options?: {
  type?: 'desktop' | 'mobile'
  onOpen?: (type: string) => void
  onClose?: (type: string) => void
}) {

  const { status } = useAccount()
  const { disconnect } = useDisconnect()
  let showModal: Ref<boolean>

  if (options?.type) {
    if (options.type === 'mobile') {
      showModal = inject(MobileModalConstant.SHOW_MODAL_UID) as Ref<boolean>
    } else {
      showModal = inject(DesktopModalConstant.SHOW_MODAL_UID) as Ref<boolean>
    }
  } else {
    if (isMobile()) {
      showModal = inject(MobileModalConstant.SHOW_MODAL_UID) as Ref<boolean>
    } else {
      showModal = inject(DesktopModalConstant.SHOW_MODAL_UID) as Ref<boolean>
    }
  }

  if (!showModal) {
    throw new Error('请先创建DesktopConnectModal实例！也不可在App.vue中使用，一定要是NeutronKitProvider的子组件才行！')
  }

  const openConnectModal = () => {
    // bug 这边不能拦截是否已连接
    showModal.value = true
  }

  const closeConnectModal = () => {
    showModal.value = false
  }

  watch(
    () => showModal.value,
    () => {
      if (!showModal.value && status.value !== 'connected') {
        disconnect()
      }
      if (!showModal.value) {
        setTimeout(() => {
          if (options && !!options.onClose) {
            options.onClose(options.type ? options.type : isMobile() ? 'mobile' : 'desktop')
          }
        }, 350)
      } else {
        if (options && !!options.onOpen) {
          options.onOpen(options.type ? options.type : isMobile() ? 'mobile' : 'desktop')
        }
      }
    }
  )

  useAccountEffect({
    onDisconnect() {
      clearLatestWalletId()
    },
  })

  return {
    state: showModal,
    openConnectModal,
    closeConnectModal,
  }
}
